package com.citcc.api.netty.xc.xcserver;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.frame.FrameDecoder;

import com.citcc.api.netty.bean.ConsuMessage;



public class XcConsuDecoder extends FrameDecoder {

    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception {
        int head_1 = buffer.getByte(0);
        //System.out.println("head_1 = " + head_1);
        int head_2 = buffer.getUnsignedByte(1);
        System.out.println("head_2===="+head_2);
        //尾部
        //int tail = buffer.getByte(buffer.capacity() - 5);
        int tail = buffer.getByte(buffer.capacity() - 1);
        //System.out.println(buffer.getByte(buffer.capacity() - 1));

        if (!(head_1 == ConsuMessage.XC_MSG_HEAD_1  && tail == ConsuMessage.XC_MSG_END)) {
            return null;
        }
        //跳过头标识
        buffer.skipBytes(2);
        //转成Message
        ConsuMessage msg = this.buildMessage(buffer);
        return msg;
    }


    private ConsuMessage buildMessage(ChannelBuffer buffer) {
        ConsuMessage msg = new ConsuMessage();
        int i = buffer.capacity();
        //读取报文长度（目前有不一致情况）
        msg.setMsgLength(buffer.readUnsignedShort());//帧长度
        msg.setMsgQfLength(buffer.readUnsignedShort());//帧长度取反
        msg.setNo(buffer.readUnsignedByte());//序号
        msg.setDataObj(buffer.readUnsignedByte());//数据对象代表枪号
        msg.setMsgId(buffer.readUnsignedByte());//1 byte  命令
        msg.setMsgBody(buffer.readBytes(buffer.capacity()-9));
        //System.out.println("after build message readable bytes:" + buffer.readableBytes());
        return msg;
    }
}
